package com.dao.impl;

import java.util.List;

import com.base.BaseDao;
import com.dao.NewDao;
import com.entity.New;
import com.entity.page.Page;
import com.entity.vo.NewVo;
import com.exception.DaoException;

public class NewDaoImpl extends BaseDao<New> implements NewDao {

	@Override
	public List<New> selectNewsByTid(Integer tid) throws DaoException {
		return executeQuery("SELECT * FROM news WHERE ntid = ?", tid);
	}

	@Override
	public New selectNewById(Integer id) throws DaoException {
		return executeQuery("SELECT * FROM news WHERE nid = ?", id).get(0);
	}

	@Override
	public Page<New> selectNewsByPage(Integer page, Integer row, NewVo newVo) throws DaoException {

		Page<New> pageInfo = new Page<New>(page, row);
		
		String sql = "SELECT * FROM news where 1=1 ";

		Object [] objs = new Object[6];//假设所有都存在
		int i = 0;
		if(newVo.getNtitle()!=""){
			sql += " AND ntitle LIKE ?";
			objs[i] = newVo.getNtitle() + "%";
			i++;
			pageInfo.getMapCond().put("ntitle", newVo.getNtitle());
		}
		if(newVo.getNauthor()!=""){
			sql += " AND nauthor = ?";
			objs[i] = newVo.getNauthor();
			i++;
			pageInfo.getMapCond().put("nauthor", newVo.getNauthor());
		}
		if(newVo.getNcreateDate()!=""){
			sql += " AND DATE_FORMAT(ncreateDate,'%Y-%m-%d') = ?";
			objs[i] = newVo.getNcreateDate();
			i++;
			pageInfo.getMapCond().put("ncreateDate", newVo.getNcreateDate());
		}
		if(newVo.getNtid()!=0){
			sql += " AND ntid = ?";
			objs[i] = newVo.getNtid();
			i++;
			pageInfo.getMapCond().put("ntid", newVo.getNtid());
		}
		sql+=" LIMIT ?,?";
		
		pageInfo.setTotalRow(executeQueryCount(sql,objs));

		objs[i++] = (page - 1) * row;
		objs[i++] = row;
		pageInfo.setList(executeQuery(sql,objs));
		return pageInfo;
	}

	@Override
	public int selectNewsCount() throws DaoException {
		return executeQueryCount("SELECT COUNT(*) FROM news where userid = ?");
	}

	@Override
	public boolean updateNewByImage(Integer id, String imgPath) throws DaoException {
		return executeUpdate("UPDATE news SET npicPath = ? WHERE nid = ?", imgPath, id) > 0;
	}

}
